//
//  WDPhotoHandler.m
//  testApp
//
//  Created by iMac on 2018/2/9.
//  Copyright © 2018年 iMac. All rights reserved.
//

#import "WDPhotoHandler.h"



@interface WDPhotoHandler()

@property (nonatomic, strong) UIImage *originImage;

@end

@implementation WDPhotoHandler

+ (instancetype)defaultHandler {
    static WDPhotoHandler *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

// 获取智能相册中的相册列表
- (NSArray<PHAssetCollection *> *)collectionsFromSmartAlbums {
    // 拿到智能相册
    NSMutableArray<PHAssetCollection *> *marr = [NSMutableArray array];
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (NSInteger i = 0; i < smartAlbums.count; i++) {
        PHCollection * collection = smartAlbums[i];
        if ([collection isKindOfClass:[PHAssetCollection class]]) {
            PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
            [marr addObject:assetCollection];
        } else {
            NSAssert(NO, @"Fetch collection not PHCollection: %@", collection);
        }
    }
    return marr.copy;
}

// 获取该相册的第一个asset对象
- (PHAsset *)firstInCollection:(PHAssetCollection *)colleciton {
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:true]];
    // 从每一个智能相册中获取到的 PHFetchResult 中包含的才是真正的资源（PHAsset）
    PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:colleciton options:options];
    if (fetchResult.count > 0) {
        return (PHAsset *)fetchResult[0];
    }
    return nil;
}

// 从一个相册中获取Assets集合, 按照创建时间排序
- (NSArray<PHAsset *> *)assetsFromCollection: (PHAssetCollection *)colleciton {
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:true]];
    // 从每一个智能相册中获取到的 PHFetchResult 中包含的才是真正的资源（PHAsset）
    PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:colleciton options:options];
    NSMutableArray<PHAsset *> * marr = [NSMutableArray array];
    for (NSInteger i = 0; i < fetchResult.count; i++) {
        PHAsset *asset = fetchResult[i];
        [marr addObject:asset];
    }
    return marr.copy;
}
// 根据一个collection 获取assets的个数
- (NSInteger)assetCountFromCollection:(PHAssetCollection *)collection {
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:true]];
    // 从每一个智能相册中获取到的 PHFetchResult 中包含的才是真正的资源（PHAsset）
    PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:options];
    return fetchResult.count;
}
// 获取一张缩略图
- (void)thumbnalImage: (PHAsset *)asset size: (CGSize)size completion:(void (^)(UIImage *, NSDictionary *))completion {
    PHImageRequestOptions *phImageRequestOptions = [[PHImageRequestOptions alloc] init];
    phImageRequestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
    // 在 PHImageManager 中，targetSize 等 size 都是使用 px 作为单位，因此需要对targetSize 中对传入的 Size 进行处理，宽高各自乘以 ScreenScale，从而得到正确的图片
    CGFloat screenScale = [UIScreen mainScreen].scale;
    CGSize imageSize = CGSizeMake(size.width * screenScale, size.height * screenScale);
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:imageSize contentMode:PHImageContentModeAspectFill options:phImageRequestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        if (completion) {
            completion(result, info);
        }
    }];
    
}
- (void)previewImage: (PHAsset *)asset completion:(void (^)(UIImage *, NSDictionary *))completion {
    CGSize size = [UIScreen mainScreen].bounds.size;
    [self thumbnalImage:asset size:size completion: completion];
}
- (void)originImage: (PHAsset *)asset completion:(void (^)(UIImage *, NSDictionary *))completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        PHImageRequestOptions *phImageRequestOptions = [[PHImageRequestOptions alloc] init];
        phImageRequestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:phImageRequestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(result, info);
                }
            });
        }];
    });
}




@end
